package JWT

import (
	"errors"
	"time"

	"github.com/dgrijalva/jwt-go"
)

//设置过期时间
const TokenExpireDuration = time.Hour * 24

//定义Token签名密钥
var MySecret = []byte("周俊的密钥")

//创建TOKEN结构体
type MyClaims struct {
	UserName string `json:"username"`
	UserId   int64  `json:"user_id"`
	jwt.StandardClaims
}

//创建Token
func GenToken(userID int64, userName string) (string, error) {
	c := MyClaims{
		UserName: userName,
		UserId:   userID,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Add(TokenExpireDuration).Unix(),
			Issuer:    "bluebell",
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, c)
	return token.SignedString(MySecret)
}

//解析Token
func ParseToken(tokenString string) (*MyClaims, error) {
	mc := new(MyClaims)
	token, err := jwt.ParseWithClaims(tokenString, mc, func(token *jwt.Token) (interface{}, error) {
		return MySecret, nil
	})
	if err != nil {
		return nil, err
	}
	if token.Valid { // 校验token
		return mc, nil
	}
	return nil, errors.New("invalid token")
}
